<template>
	<xn-form-container title="资产领用申请" :width="900" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="formRef" :model="formModel" :rules="formRules" layout="vertical">
			<!-- 资产列表选择 -->
			<a-form-item label="资产列表" name="assets" required>
				<a-button @click="categoryModalVisible = true">选择资产</a-button>
				<div v-if="selectedAssets.length > 0" class="selected-assets-container">
					<a-table :data-source="selectedAssets" :pagination="false" size="small" class="asset-table">
						<a-table-column title="品类" dataIndex="assetCategoryName" key="assetCategoryName" />
						<a-table-column title="图片" key="image">
							<template #default="{ record }">
								<a-image
									v-if="record.image"
									:src="jdOssBaseUrl + record.image"
									:width="40"
									:height="40"
									:preview="false"
								/>
								<span v-else>无图片</span>
							</template>
						</a-table-column>
						<a-table-column title="规格" dataIndex="spec" key="spec" />
						<a-table-column title="编号" dataIndex="assetCode" key="assetCode" />
						<a-table-column title="名称" dataIndex="assetName" key="assetName" />
						<a-table-column title="备注" key="remark">
							<template #default="{ record }">
								<a-form-item-rest>
									<a-input v-model:value="record.remark" placeholder="请输入备注" size="small" />
								</a-form-item-rest>
							</template>
						</a-table-column>
						<a-table-column title="操作" key="action">
							<template #default="{ record }">
								<a-button type="link" @click="removeSelectedAsset(record)" size="small"> 移除</a-button>
							</template>
						</a-table-column>
					</a-table>
				</div>
			</a-form-item>
			<a-form-item label="代为领取" name="onBehalf">
				<a-checkbox v-model:checked="onBehalf" @change="handleOnBehalfChange"> 是否代为领取</a-checkbox>
			</a-form-item>
			<a-form-item label="领取人" name="issueId" v-if="onBehalf">
				<a-input @click="userSelectorPlusRef.showUserPlusModal()" :value="selectedUser?.name || ''" readonly />
				<div v-if="selectedUser" class="selected-user-info">{{ selectedUser.name }} ({{ selectedUser.account }})</div>
			</a-form-item>
			<a-form-item label="领取部门" name="deptId" v-if="onBehalf">
				<a-input :value="selectedUser?.orgName || ''" disabled />
			</a-form-item>
			<a-form-item label="签名确认" name="signatureImg" required>
				<a-button @click="xnSignNameRef?.show()" class="xn-mr8">打开签名板</a-button>
				<a-button v-if="signatureImg" @click="clearSignature">清除签名</a-button>
				<br />
				<div v-if="signatureImg" class="signature-preview">
					<img :src="signatureImg" alt="签名预览" class="signature-img" />
				</div>
				<div v-else class="no-signature">
					<span>暂无签名</span>
				</div>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
		<!-- 资产选择模态框 -->
		<AssetsModel
			v-model:visible="categoryModalVisible"
			:selected-assets="selectedAssets"
			@confirm="onAssetSelectConfirm"
			@cancel="categoryModalVisible = false"
			ref="assetsModelRef"
		/>
		<!--用户选择模态框-->
		<UserSelectorPlus
			ref="userSelectorPlusRef"
			data-type="object"
			:user-show="false"
			:radio-model="true"
			@onBack="userCallBack"
		/>
		<!-- 签名模态框 -->
		<XnSignName ref="xnSignNameRef" @successful="handleSignatureSuccess" />
	</xn-form-container>
</template>

<script setup>
	import assetsIssueApi from '@/api/hrms/assets/issue/assetsIssueApi'
	import tool from '@/utils/tool'
	import Promise from 'lodash-es/_Promise'
	import UserSelectorPlus from '@/components/Selector/userSelectorPlus.vue'
	import AssetsModel from '@/views/hrms/assets/issue/assetsModel.vue'
	import XnSignName from '@/components/XnSignName/index.vue'

	// 默认是关闭状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const assetsModelRef = ref()
	const userSelectorPlusRef = ref()
	const xnSignNameRef = ref()
	const submitLoading = ref(false)

	// 获取当前用户信息
	const userInfo = tool.data.get('USER_INFO')

	const jdOssBaseUrl = 'https://s3.cn-north-1.jdcloud-oss.com/'
	// 签名图片
	const signatureImg = ref(userInfo?.signature || '')

	// 已选择的用户，默认为当前用户
	const selectedUser = ref({
		id: userInfo?.id,
		name: userInfo?.name || '',
		account: userInfo?.account || '',
		orgId: userInfo?.orgId,
		orgName: userInfo?.orgName || ''
	})

	// 代为领取
	const onBehalf = ref(false)

	// 表单数据模型（现在为空对象）
	const formModel = ref({})

	// 已选择的资产列表
	const selectedAssets = ref([])
	// 资产模态框相关
	const categoryModalVisible = ref(false)

	// 表单验证规则
	const formRules = {
		assets: [
			{
				required: true,
				message: '请选择资产',
				trigger: ['change'],
				validator: (_, value) => {
					if (!selectedAssets.value || selectedAssets.value.length === 0) {
						return Promise.reject('请选择资产')
					}
					return Promise.resolve()
				}
			}
		],
		issueId: [
			{
				required: true,
				message: '请选择领取人',
				trigger: ['change'],
				validator: (_, value) => {
					if (onBehalf.value && !selectedUser.value?.id) {
						return Promise.reject('请选择领取人')
					}
					return Promise.resolve()
				}
			}
		],
		deptId: [
			{
				required: true,
				message: '请选择领取部门',
				trigger: ['change'],
				validator: (_, value) => {
					if (onBehalf.value && !selectedUser.value?.orgId) {
						return Promise.reject('请选择领取部门')
					}
					return Promise.resolve()
				}
			}
		],
		signatureImg: [
			{
				required: true,
				message: '请签名确认',
				trigger: ['change'],
				validator: (_, value) => {
					if (!signatureImg.value) {
						return Promise.reject('请签名确认')
					}
					return Promise.resolve()
				}
			}
		]
	}

	// 处理签名确认
	const handleSignatureSuccess = (imgData) => {
		signatureImg.value = imgData
		// 触发签名验证
		if (formRef.value) {
			formRef.value.validateFields(['signatureImg'])
		}
	}

	// 清除签名
	const clearSignature = () => {
		signatureImg.value = ''
		// 触发签名验证
		if (formRef.value) {
			formRef.value.validateFields(['signatureImg'])
		}
	}

	// 处理代为领取变化
	const handleOnBehalfChange = (checked) => {
		if (!checked) {
			// 取消代为领取时，重置选择的用户为当前用户
			selectedUser.value = {
				id: userInfo?.id,
				name: userInfo?.name || '',
				account: userInfo?.account || '',
				orgId: userInfo?.orgId,
				orgName: userInfo?.orgName || ''
			}
		}
		// 触发验证
		if (formRef.value) {
			formRef.value.validateFields(['issueId', 'deptId'])
		}
	}

	// 用户选择回调
	const userCallBack = (users) => {
		if (users && users.length > 0) {
			// 取第一条数据
			selectedUser.value = users[0]
			// 触发验证
			if (formRef.value) {
				formRef.value.validateFields(['issueId', 'deptId'])
			}
		}
	}

	// 资产选择确认
	const onAssetSelectConfirm = (assets) => {
		// 为每个资产添加备注字段
		selectedAssets.value = assets.map((asset) => ({
			...asset,
			remark: ''
		}))
		categoryModalVisible.value = false
		// 触发资产验证
		if (formRef.value) {
			formRef.value.validateFields(['assets'])
		}
	}

	// 移除已选择的资产
	const removeSelectedAsset = (asset) => {
		selectedAssets.value = selectedAssets.value.filter((a) => a?.assetCategory !== asset?.assetCategory)
		// 如果资产列表为空，触发验证
		if (selectedAssets.value.length === 0 && formRef.value) {
			formRef.value.validateFields(['assets'])
		}
	}

	// 打开抽屉
	const onOpen = () => {
		visible.value = true
		selectedAssets.value = []
		// 初始化时设置为当前用户的签名
		signatureImg.value = userInfo?.signature || ''
		// 初始化时设置为当前用户
		selectedUser.value = {
			id: userInfo?.id,
			name: userInfo?.name || '',
			account: userInfo?.account || '',
			orgId: userInfo?.orgId,
			orgName: userInfo?.orgName || ''
		}
		onBehalf.value = false
	}

	// 关闭抽屉
	const onClose = () => {
		if (formRef.value) {
			formRef.value.resetFields()
		}
		visible.value = false
		selectedAssets.value = []
		onBehalf.value = false
	}

	// 验证并提交数据
	const onSubmit = () => {
		if (!formRef.value) return
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				// 构建只包含id和remark的资产列表
				const issueDetailList = selectedAssets.value.map((asset) => ({
					assetId: asset.id, // 只传递资产ID
					remark: asset.remark // 只传递备注
				}))

				const submitData = {
					issueDetailList: issueDetailList,
					signatureImg: signatureImg.value,
					issueId: selectedUser.value.id,
					issueName: selectedUser.value.name,
					deptId: selectedUser.value.orgId,
					assetStatus: 1
				}
				assetsIssueApi
					.addIssue(submitData)
					.then(() => {
						onClose()
						emit('successful')
						submitLoading.value = false
					})
					.catch((error) => {
						console.error('提交失败:', error)
						submitLoading.value = false
					})
			})
			.catch((error) => {
				console.error('表单验证失败:', error)
			})
	}

	// 暴露方法给父组件
	defineExpose({
		onOpen,
		onClose
	})
</script>

<style scoped>
	.selected-assets-container {
		margin-top: 10px;
	}

	.asset-table {
		margin-top: 10px;
	}

	.selected-user-info {
		margin-top: 8px;
		padding: 8px;
		background-color: #f5f5f5;
		border-radius: 4px;
		font-size: 12px;
	}

	.signature-preview {
		margin-top: 10px;
	}

	.signature-img {
		max-width: 300px;
		max-height: 150px;
		border: 1px solid #d9d9d9;
		border-radius: 4px;
		padding: 5px;
	}

	.no-signature {
		margin-top: 10px;
		color: #999;
		font-style: italic;
	}

	.xn-mr8 {
		margin-right: 8px;
	}
</style>
